/**
 * junixsocket
 * <p>
 * Copyright 2009-2021 Christian Kohlschütter
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.liuyun;

import org.newsclub.net.unix.AFUNIXSocket;
import org.newsclub.net.unix.AFUNIXSocketAddress;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.SocketException;
import java.util.logging.Logger;

/**
 * A simple demo client to call docker api.
 *
 * @author Christian Kohlschütter
 */
public class DockerClientDemo {
    private static final Logger LOGGER = Logger.getLogger(DockerClientDemo.class.getName());
    private static final String SOCK_FILE = "/var/run/docker.sock";

    public static void main(String[] args) throws IOException {
        final File socketFile = new File(SOCK_FILE);

        try (AFUNIXSocket sock = AFUNIXSocket.newInstance()) {
            try {
                sock.connect(new AFUNIXSocketAddress(socketFile));
            } catch (SocketException e) {
                System.out.println("Cannot connect to server. Have you started it?");
                System.out.println();
                throw e;
            }
            System.out.println("Connected");

            try (BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                 PrintWriter w = new PrintWriter(sock.getOutputStream())) {
                w.println("GET /v1.39/images/json HTTP/1.1");
                w.println("Host: http");
                w.println("Accept: */*");
                w.println("");
                w.flush();
                w.close();
                // 获取返回结果
                LOGGER.info("---- Docker Response ----");

                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
            }
        }

        System.out.println("End of communication.");
    }
}
